<template>
	<view class="notification-container">
		<!-- Tab切换区域 -->
		<view class="tab-section">
			<view 
				class="tab-item" 
				:class="{ active: currentTab === 'unread' }"
				@tap="switchTab('unread')"
			>
				<text>未读</text>
			</view>
			<view 
				class="tab-item" 
				:class="{ active: currentTab === 'all' }"
				@tap="switchTab('all')"
			>
				<text>所有</text>
			</view>
		</view>

		<!-- 搜索区域 -->
		<view class="search-section">
			<view class="search-box">
				<input 
					type="text"
					v-model="searchText"
					placeholder="请输入通知主题"
					class="search-input"
					@input="onSearch"
				/>
				<image 
					v-if="searchText"
					src="/static/images/clear.svg" 
					class="clear-icon" 
					mode="aspectFit"
					@tap="clearSearch"
				></image>
			</view>
		</view>

		<!-- 列表区域 -->
		<scroll-view 
			class="notification-scroll"
			scroll-y="true"
			@scrolltolower="loadMore"
			@refresherrefresh="onRefresh"
			:refresher-enabled="true"
			:refresher-triggered="isRefreshing"
		>
			<!-- 空状态 -->
			<view v-if="notificationList.length === 0 && !isLoading" class="empty-state">
				<image 
					src="/static/images/no-data.svg" 
					mode="aspectFit" 
					class="empty-image"
				></image>
				<text class="empty-text">暂无通知数据</text>
			</view>

			<!-- 通知列表 -->
			<view v-else class="notification-list">
				<view 
					class="notification-card" 
					v-for="(notification, index) in notificationList" 
					:key="index"
					@tap="goToDetail(notification)"
				>
					<view class="card-content">
						<view class="first-line">
							<text class="notification-title text-ellipsis">{{ notification.subject }}</text>
							<text class="create-time">{{ formatTime(notification.createdTime) }}</text>
						</view>
						<view class="second-line">
							<text class="notification-type">{{ formatType(notification.type) }}</text>
							<view class="action-icons">
								<image 
									:src="notification.status === 'READ' ? '/static/images/read-2.svg' : '/static/images/read.svg'"
									mode="aspectFit" 
									class="action-icon"
									@tap.stop="notification.status !== 'READ' && markAsRead(notification)"
								></image>
								<image 
									src="/static/images/deleted.svg" 
									mode="aspectFit" 
									class="action-icon"
									@tap.stop="deleteNotification(notification)"
								></image>
							</view>
						</view>
					</view>
				</view>

				<!-- 加载状态 -->
				<view v-if="isLoading" class="loading-more">
					<text>加载中...</text>
				</view>

				<!-- 无更多数据 -->
				<view v-if="!hasMore && notificationList.length > 0" class="no-more">
					<text>没有更多数据了</text>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import request from '@/utils/request.js'
import { formatTime } from '@/utils/timeUtils.js'

export default {
	data() {
		return {
			currentTab: 'unread',
			notificationList: [],
			page: 0,
			pageSize: 10,
			hasMore: true,
			isLoading: false,
			isRefreshing: false,
			searchText: '',
			searchTimer: null,
			typeMap: {
				'ALARM': '告警',
				'ALARM_ASSIGNMENT': '告警分配',
				'ALARM_COMMENT': '告警评论',
				'API_USAGE_LIMIT': 'API使用限制',
				'DEVICE_ACTIVITY': '设备活动',
				'EDGE_COMMUNICATION_FAILURE': '边缘通信失败',
				'EDGE_CONNECTION': '边缘连接',
				'ENTITIES_LIMIT': '实体限制',
				'ENTITY_ACTION': '实体操作',
				'GENERAL': '通用',
				'PLATFORM_VERSION': '平台版本',
				'RATE_LIMITS': '速率限制',
				'RULE_ENGINE_COMPONENT_LIFECYCLE_EVENT': '规则引擎组件生命周期事件',
				'RULE_NODE': '规则节点',
				'TASK_PROCESSING_FAILURE': '任务处理失败'
			}
		}
	},

	onLoad() {
		this.fetchNotifications()
	},

	methods: {
		formatTime,

		// 切换Tab
		switchTab(tab) {
			if (this.currentTab === tab) return
			this.currentTab = tab
			this.page = 0
			this.notificationList = []
			this.hasMore = true
			this.fetchNotifications(true)
		},

		// 获取通知列表
		async fetchNotifications(isRefresh = false) {
			if (this.isLoading) return

			try {
				this.isLoading = true
				const params = {
					pageSize: this.pageSize,
					page: this.page,
					textSearch: this.searchText,
					sortProperty: 'createdTime',
					sortOrder: 'DESC',
					unreadOnly: this.currentTab === 'unread'
				}

				const result = await request.get('/api/notifications', params)
				
				if (result && result.data) {
					if (isRefresh) {
						this.notificationList = result.data
					} else {
						this.notificationList = [...this.notificationList, ...result.data]
					}
					this.hasMore = result.hasNext || false
				}
			} catch (error) {
				console.error('获取通知列表失败：', error)
				uni.showToast({
					title: '获取通知列表失败',
					icon: 'none'
				})
			} finally {
				this.isLoading = false
				if (isRefresh) {
					this.isRefreshing = false
					uni.stopPullDownRefresh()
				}
			}
		},

		// 搜索处理
		onSearch() {
			if (this.searchTimer) {
				clearTimeout(this.searchTimer)
			}
			this.searchTimer = setTimeout(() => {
				this.page = 0
				this.notificationList = []
				this.hasMore = true
				this.fetchNotifications(true)
			}, 300)
		},

		// 清除搜索
		clearSearch() {
			this.searchText = ''
			this.onSearch()
		},

		// 下拉刷新
		async onRefresh() {
			if (this.isRefreshing || this.isLoading) return
			this.isRefreshing = true
			this.page = 0
			await this.fetchNotifications(true)
		},

		// 加载更多
		async loadMore() {
			if (!this.hasMore || this.isLoading || this.isRefreshing) return
			this.page++
			await this.fetchNotifications()
		},

		// 标记已读
		async markAsRead(notification) {
			try {
				await request.put(`/api/notification/${notification.id.id}/read`)
				uni.showToast({
					title: '标记已读成功',
					icon: 'success'
				})
				this.onRefresh()
			} catch (error) {
				console.error('标记已读失败：', error)
				uni.showToast({
					title: '标记已读失败',
					icon: 'none'
				})
			}
		},

		// 删除通知
		async deleteNotification(notification) {
			try {
				await request.delete(`/api/notification/${notification.id.id}`)
				uni.showToast({
					title: '删除成功',
					icon: 'success'
				})
				this.onRefresh()
			} catch (error) {
				uni.showToast({
					title: '删除失败',
					icon: 'none'
				})
			}
		},

		// 跳转到详情页
		goToDetail(notification) {
			uni.navigateTo({
				url: '/pages/more/notification/notificationDetail?id=' + notification.id.id,
				success: function(res) {
					res.eventChannel.emit('notificationData', { data: notification })
				}
			})
		},

		// 格式化通知类型显示
		formatType(type) {
			return this.typeMap[type] || type
		}
	}
}
</script>

<style>
.notification-container {
	min-height: 100vh;
	background-color: #f5f5f5;
}

.tab-section {
	display: flex;
	background-color: #fff;
	padding: 20rpx 20rpx 10rpx;
	justify-content: center;
	gap: 20rpx;
}

.tab-item {
	flex: 0 0 auto;
	padding: 16rpx 100rpx;
	font-size: 28rpx;
	color: #666;
	background-color: #f5f5f5;
	border-radius: 40rpx;
	position: relative;
}

.tab-item.active {
	color: #fff;
	background-color: #305680;
	font-weight: 500;
}

.tab-item.active::after {
	display: none;
}

.search-section {
	background-color: #fff;
	padding: 10rpx 20rpx;
}

.search-box {
	display: flex;
	align-items: center;
	background-color: #f5f5f5;
	border-radius: 8rpx;
	padding: 16rpx 20rpx;
	position: relative;
}

.search-input {
	flex: 1;
	font-size: 28rpx;
	padding-right: 60rpx;
}

.clear-icon {
	width: 40rpx;
	height: 40rpx;
	position: absolute;
	right: 20rpx;
	top: 50%;
	transform: translateY(-50%);
}

.notification-scroll {
	height: calc(100vh - 178rpx);
}

.notification-list {
	padding: 20rpx;
}

.notification-card {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.card-content {
	display: flex;
	flex-direction: column;
	gap: 24rpx;
}

.first-line {
	display: flex;
	justify-content: space-between;
	align-items: center;
	gap: 20rpx;
}

.notification-title {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
	max-width: 60%;
	flex-shrink: 1;
}

.text-ellipsis {
	overflow: hidden;
	white-space: nowrap;
	text-overflow: ellipsis;
}

.create-time {
	font-size: 26rpx;
	color: #999;
	flex-shrink: 0;
}

.second-line {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.notification-type {
	font-size: 26rpx;
	color: #666;
}

.action-icons {
	display: flex;
	gap: 40rpx;
}

.action-icon {
	width: 40rpx;
	height: 40rpx;
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
}

.empty-image {
	width: 240rpx;
	height: 240rpx;
	margin-bottom: 30rpx;
}

.empty-text {
	font-size: 28rpx;
	color: #999;
}

.loading-more, 
.no-more {
	text-align: center;
	padding: 30rpx 0;
	color: #999;
	font-size: 24rpx;
}
</style>
